<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\material;

use app\enum\CommonEnum;
use app\model\ClientCashRateModel;
use app\model\ClientMaterialCostModel;
use app\model\FileUploadModel;
use app\model\KsVideoModel;
use app\model\OeVideoModel;
use app\model\QqVideoModel;
use app\model\VideoAdvertiserDailyCostModel;
use app\model\VideoDailyCostCalculationModel;
use app\model\VideoDailyCostConfigModel;
use app\model\VideoDailyCostMaterialModel;
use app\model\VideoDailyCostModel;
use app\model\VideoModel;
use app\model\VideoNinetyCostModel;
use app\model\VideoNinetyDailyCostModel;
use app\model\VideoVersionDailyCostModel;
use app\model\VideoVersionNinetyDailyCostModel;
use app\model\ZcStoreModel;
use app\model\ZcTaskModel;
use app\service\BaseService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Db;
use think\Model;

abstract class MaterialCostService extends BaseService
{
    /**
     * @var int 运行日期
     */
    protected static int $runDate;

    /**
     * @var int 脚本Tag
     */
    protected static int $runNum;

    /**
     * @var int 媒体id
     */
    protected static int $mediaId;

    /**
     * @var Model 报表模型
     */
    protected static Model $reportModel;

    /**
     * 视频中间表消耗汇总.
     */
    public static function setClientMaterialCost(): bool
    {
        $date = self::$runDate;
        $mediaId = self::$mediaId;
        $data = self::getReportData();
        $model = self::getReportModel();
        if ($data === false) {
            return false;
        }
        if (! $data) {
            return true;
        }
        Db::startTrans();
        try {
            foreach ($data as $val) {
                if ($val->is_sync != $val::SYNC_DISABLE) {
                    // 执行过的不再执行
                    continue;
                }
                if (! floatval($val->cost)) {
                    $model->where('id', $val['id'])->update(['is_sync' => 1]);
                    continue;
                }
                if (! $val['signature']) {
                    // 无md5，不处理
                    continue;
                }
                // 查询file_id
                $fileId = FileUploadModel::where('file_md5', $val['signature'])->value('id');
                // 查询客户比例
                $cashRate = ClientCashRateModel::where('client_id', $val['client_id'])
                    ->where('date_time', $date)
                    ->where('media_id', $mediaId)
                    ->value('valid_rate');
                $cashRate = $cashRate ?: 0;
                // 计算现金金额
                if ($mediaId == CommonEnum::QQ_MEDIA) {
                    $val['cost'] = $val['cost'] / 100;  // 广点通单位分
                }
                $cashCost = $val['cost'] * $cashRate;

                if ($fileId) {
                    // 存video_advertiser_daily表
                    $hasVaData = VideoAdvertiserDailyCostModel::where('file_id', $fileId)
                        ->where('stat_date', self::getStatDate())
                        ->where('media_id', $mediaId)
                        ->find();
                    if ($hasVaData) {
                        VideoAdvertiserDailyCostModel::where('id', $hasVaData['id'])
                            ->update(['cost' => $cashCost]);
                    } else {
                        $videoAdvertiserData = [
                            'file_id' => $fileId,
                            'media_id' => $mediaId,
                            'advertiser_id' => $val['advertiser_id'],
                            'stat_date' => self::getStatDate(),
                            'cost' => $cashCost,
                        ];
                        VideoAdvertiserDailyCostModel::create($videoAdvertiserData);
                    }
                }

                // 判断是否已存在
                $isHas = ClientMaterialCostModel::where('stat_date', $date)
                    ->where('client_id', $val['client_id'])
                    ->where('media_id', $mediaId)
                    ->where('signature', $val['signature'])
                    ->find();
                if ($isHas) {
                    // 已存在加消耗金额
                    ClientMaterialCostModel::where('id', $isHas['id'])->inc('cost', (float) $val['cost'])->update();
                    ClientMaterialCostModel::where('id', $isHas['id'])->inc('cash_cost', (float) $cashCost)->update();
                } else {
                    $dataIn = [
                        'client_id' => $val['client_id'],
                        'signature' => $val['signature'],
                        'media_id' => $mediaId,
                        'file_id' => $fileId ? $fileId : 0,
                        'stat_date' => $date,
                        'cost' => $val['cost'],
                        'cash_cost' => $cashCost,
                    ];
                    ClientMaterialCostModel::create($dataIn);
                }
                // 修改报表状态
                $model->where('id', $val['id'])->update(['is_sync' => 1]);
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取视频所有版本file_id.
     * @param int $fileId 文件id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getVideoAllVersionIds(int $fileId)
    {
        $video = VideoModel::where('file_id', $fileId)->find();
        if ($video['subtask_id'] > 0) {
            $fileIds = VideoModel::where('subtask_id', $video['subtask_id'])->column('file_id');
        } else {
            $fileIds = VideoModel::where('parent_id', $video['parent_id'])->column('file_id');
        }
        return $fileIds;
    }

    /**
     * 获取视频指定日期媒体消耗.
     * @param array $fileIds 文件id
     * @param string $startDate 开始日期
     * @param string $endDate 结束日期
     * @return int[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getVideoCostByFileIds(array $fileIds, string $startDate, string $endDate): array
    {
        $data = [
            'oe_cost' => 0,
            'ks_cost' => 0,
            'qq_cost' => 0,
        ];
        if ($startDate == $endDate) {
            $datas = VideoDailyCostModel::whereIn('file_id', $fileIds)
                ->where('stat_date', $startDate)
                ->select()->toArray();
        } else {
            $datas = VideoDailyCostModel::whereIn('file_id', $fileIds)
                ->whereBetweenTime('stat_date', $startDate, $endDate)
                ->select()->toArray();
        }
        foreach ($datas as $val) {
            if ($val['media_id'] == CommonEnum::OE_MEDIA) {
                $data['oe_cost'] += $val['cost'];
            } elseif ($val['media_id'] == CommonEnum::KS_MEDIA) {
                $data['ks_cost'] += $val['cost'];
            } elseif ($val['media_id'] == CommonEnum::QQ_MEDIA) {
                $data['qq_cost'] += $val['cost'];
            }
        }

        return $data;
    }

    /**
     * 获取视频指定日期90天媒体消耗.
     * @param array $fileIds 文件id
     * @param string $startDate 开始日期
     * @param string $endDate 结束日期
     * @return int[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getVideoNinetyCostByFileIds(array $fileIds, string $startDate, string $endDate): array
    {
        $data = [
            'oe_cost' => 0,
            'ks_cost' => 0,
            'qq_cost' => 0,
        ];
        if ($startDate == $endDate) {
            $datas = VideoNinetyDailyCostModel::whereIn('file_id', $fileIds)
                ->where('stat_date', $startDate)
                ->select()->toArray();
        } else {
            $datas = VideoNinetyDailyCostModel::whereIn('file_id', $fileIds)
                ->whereBetweenTime('stat_date', $startDate, $endDate)
                ->select()->toArray();
        }

        foreach ($datas as $val) {
            if ($val['media_id'] == CommonEnum::OE_MEDIA) {
                $data['oe_cost'] += $val['cost'];
            } elseif ($val['media_id'] == CommonEnum::KS_MEDIA) {
                $data['ks_cost'] += $val['cost'];
            } elseif ($val['media_id'] == CommonEnum::QQ_MEDIA) {
                $data['qq_cost'] += $val['cost'];
            }
        }
        return $data;
    }

    /**
     * 视频消耗汇总.
     * @param int $date 日期
     * @param int $mediaId 媒体id
     * @param int $fileId 文件id
     * @return array|mixed|string|true
     */
    public static function cacheVideoCost(int $date, int $mediaId, int $fileId = 0)
    {
        Db::startTrans();
        try {
            $where = [
                ['b.stat_date', '=', $date],
                ['b.media_id', '=', $mediaId],
            ];
            if ($fileId) {
                $where[] = ['a.file_id', '=', $fileId];
            }
            $dateStr = date('Y-m-d', strtotime("{$date}"));
            $date_datas = VideoModel::alias('a')
                ->join('habo_client_material_cost b', 'a.signature=b.signature')
                ->where($where)
                ->field('SUM(b.cash_cost) AS sum_cost,a.file_id,a.task_id,a.product_id,b.stat_date')
                ->group('a.file_id')
                ->select()->toArray();
            foreach ($date_datas as $dd) {
                $dd['stat_date'] = $dateStr;
                $where = [
                    'file_id' => $dd['file_id'],
                    'media_id' => $mediaId,
                    'stat_date' => $dd['stat_date'],
                ];
                // 外采视频消耗按比例计算
                $dd = self::videoCostRateOperation($dd);
                $data = [
                    'file_id' => $dd['file_id'],
                    'cost' => $dd['sum_cost'],
                    'media_id' => $mediaId,
                    'stat_date' => $dd['stat_date'],
                ];
                // 判断是否存在90天起消日记录，不存在则新增
                $ninetyData = VideoNinetyCostModel::where('file_id', $dd['file_id'])
                    ->find();
                if ($ninetyData) {
                    // 是否进90天消耗表内
                    if ($ninetyData['start_date'] <= $dd['stat_date'] && $ninetyData['end_date'] >= $dd['stat_date']) {
                        $isHas = VideoNinetyDailyCostModel::where($where)->find();
                        if (! $isHas) {
                            VideoNinetyDailyCostModel::create($data);
                        } else {
                            VideoNinetyDailyCostModel::where('id', $isHas['id'])->update($data);
                        }
                    }
                } else {
                    // 新增记录
                    $ninetyData = [
                        'file_id' => $dd['file_id'],
                        'start_date' => $dd['stat_date'],
                        'end_date' => date('Y-m-d', strtotime($dd['stat_date'] . ' +90 days')),
                        'all_cost' => $dd['sum_cost'],
                    ];
                    if ($mediaId == CommonEnum::OE_MEDIA) {
                        $ninetyData['oe_cost'] = $dd['sum_cost'];
                    } elseif ($mediaId == CommonEnum::KS_MEDIA) {
                        $ninetyData['ks_cost'] = $dd['sum_cost'];
                    } elseif ($mediaId == CommonEnum::QQ_MEDIA) {
                        $ninetyData['qq_cost'] = $dd['sum_cost'];
                    }
                    $res = VideoNinetyCostModel::create($ninetyData);
                    if ($res) {
                        // 是否进90天消耗表内
                        $isHas = VideoNinetyDailyCostModel::where($where)->find();
                        if (! $isHas) {
                            VideoNinetyDailyCostModel::create($data);
                        } else {
                            VideoNinetyDailyCostModel::where('id', $isHas['id'])->update($data);
                        }
                    }
                }

                $row = VideoDailyCostModel::where($where)->find();
                if (! $row) {
                    VideoDailyCostModel::create($data);
                } else {
                    unset($data['file_id'], $data['media_id'], $data['stat_date']);
                    VideoDailyCostModel::where('id', $row['id'])->update($data);
                }
            }
            unset($date_datas);
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return self::getError($e->getMessage());
        }
    }

    /**
     * 视频消耗汇总.
     * @param int $date 日期
     * @param int $mediaId 媒体id
     * @param int $fileId 文件id
     * @return array|mixed|string|true
     */
    public static function cacheTodayVideoCost(int $date, int $mediaId, int $fileId = 0)
    {
        Db::startTrans();
        try {
            $where = [
                ['b.stat_date', '=', $date],
                ['d.date_time', '=', $date],
                ['d.media_id', '=', $mediaId],
            ];
            if ($fileId) {
                $where[] = ['a.file_id', '=', $fileId];
            }
            $date_datas = VideoModel::alias('a')
                ->join(['habo_ks_material_daily_report' => 'b'], 'a.signature=b.signature')
                ->join(['habo_video_ninety_cost' => 'c'], 'a.file_id=c.file_id')
                ->join(['habo_client_cash_rate' => 'd'], 'a.client_id=d.client_id')
                ->where($where)
                ->field('SUM(b.cost) AS sum_cost,a.file_id,a.task_id,a.product_id,b.stat_date,a.client_id,d.valid_rate')
                ->group('a.file_id')
                ->select()->toArray();
            $dateStr = date('Y-m-d', strtotime(strval($date)));
            foreach ($date_datas as $dd) {
                // 查询客户
                $dd['stat_date'] = $dateStr;
                $where = [
                    'file_id' => $dd['file_id'],
                    'media_id' => $mediaId,
                    'stat_date' => $dd['stat_date'],
                ];
                // 外采视频消耗按比例计算
                $dd = self::videoCostRateOperation($dd);
                $data = [
                    'file_id' => $dd['file_id'],
                    'cost' => $dd['sum_cost'] * $dd['valid_rate'],     // 现金消耗
                    'media_id' => $mediaId,
                    'stat_date' => $dd['stat_date'],
                ];
                // 判断是否存在90天起消日记录，不存在则新增
                $ninetyData = VideoNinetyCostModel::where('file_id', $dd['file_id'])
                    ->find();
                if ($ninetyData) {
                    // 是否进90天消耗表内
                    if ($ninetyData['start_date'] <= $dd['stat_date'] && $ninetyData['end_date'] >= $dd['stat_date']) {
                        $isHas = VideoNinetyDailyCostModel::where($where)->find();
                        if (! $isHas) {
                            VideoNinetyDailyCostModel::create($data);
                        } else {
                            VideoNinetyDailyCostModel::where('id', $isHas['id'])->update($data);
                        }
                    }
                } else {
                    // 新增记录
                    $ninetyData = [
                        'file_id' => $dd['file_id'],
                        'start_date' => $dd['stat_date'],
                        'end_date' => date('Y-m-d', strtotime($dd['stat_date'] . ' +90 days')),
                        'all_cost' => $dd['sum_cost'],
                    ];
                    if ($mediaId == CommonEnum::OE_MEDIA) {
                        $ninetyData['oe_cost'] = $dd['sum_cost'];
                    } elseif ($mediaId == CommonEnum::KS_MEDIA) {
                        $ninetyData['ks_cost'] = $dd['sum_cost'];
                    } elseif ($mediaId == CommonEnum::QQ_MEDIA) {
                        $ninetyData['qq_cost'] = $dd['sum_cost'];
                    }
                    $res = VideoNinetyCostModel::create($ninetyData);
                    if ($res) {
                        // 是否进90天消耗表内
                        $isHas = VideoNinetyDailyCostModel::where($where)->find();
                        if (! $isHas) {
                            VideoNinetyDailyCostModel::create($data);
                        } else {
                            VideoNinetyDailyCostModel::where('id', $isHas['id'])->update($data);
                        }
                    }
                }

                $row = VideoDailyCostModel::where($where)->find();
                if (! $row) {
                    VideoDailyCostModel::create($data);
                } else {
                    unset($data['file_id'], $data['media_id'], $data['stat_date']);
                    VideoDailyCostModel::where('id', $row['id'])->update($data);
                }
            }
            unset($date_datas);
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return self::getError($e->getMessage());
        }
    }

    /**
     * 非本地视频消耗汇总.
     * @param int $date 日期
     * @param int $mediaId 媒体id
     * @param null|int $signature md5
     * @return array|mixed|string|true
     */
    public static function cacheVideoCostMaterial(int $date, int $mediaId, int $signature = null)
    {
        Db::startTrans();
        try {
            $where = [
                ['stat_date', '=', $date],
                ['media_id', '=', $mediaId],
                ['file_id', '=', 0],
            ];
            if ($signature) {
                $where[] = ['signature', '=', $signature];
            }
            $date_datas = ClientMaterialCostModel::where($where)
                ->field('client_id,signature,SUM(cost) AS sum_cost,SUM(cash_cost) AS sum_cash_cost,stat_date')
                ->group('signature')
                ->select()->toArray();
            foreach ($date_datas as $dd) {
                $where = [
                    'signature' => $dd['signature'],
                    'media_id' => $mediaId,
                    'stat_date' => $dd['stat_date'],
                ];
                $data = [
                    'client_id' => $dd['client_id'],
                    'signature' => $dd['signature'],
                    'cost' => $dd['sum_cost'],
                    'cash_cost' => $dd['sum_cash_cost'],
                    'media_id' => $mediaId,
                    'stat_date' => $dd['stat_date'],
                ];
                // 查询文件名、地址等数据
                if ($mediaId == CommonEnum::OE_MEDIA) {
                    $videoData = OeVideoModel::where('signature', $dd['signature'])->find();
                    if ($videoData) {
                        $data['file_name'] = $videoData['filename'];
                        $data['file_url'] = $videoData['url'];
                        $data['cover_url'] = $videoData['poster_url'];
                        $data['create_time'] = strtotime($videoData['create_time']);
                    }
                } elseif ($mediaId == CommonEnum::KS_MEDIA) {
                    $videoData = KsVideoModel::where('signature', $dd['signature'])->find();
                    if ($videoData) {
                        $data['file_name'] = $videoData['photo_name'];
                        $data['file_url'] = $videoData['url'];
                        $data['cover_url'] = $videoData['cover_url'];
                        $data['create_time'] = strtotime($videoData['upload_time']);
                    }
                } elseif ($mediaId == CommonEnum::QQ_MEDIA) {
                    $videoData = QqVideoModel::where('signature', $dd['signature'])->find();
                    if ($videoData) {
                        $data['file_name'] = $videoData['description'];
                        $data['file_url'] = $videoData['preview_url'];
                        $data['cover_url'] = $videoData['key_frame_image_url'];
                        $data['create_time'] = $videoData['created_time'];
                    }
                }
                $row = VideoDailyCostMaterialModel::where($where)->find();
                if (! $row) {
                    VideoDailyCostMaterialModel::create($data);
                } else {
                    unset($data['signature'], $data['media_id'], $data['stat_date']);
                    VideoDailyCostMaterialModel::where('id', $row['id'])->update($data);
                }
            }
            unset($date_datas);
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return self::getError($e->getMessage());
        }
    }

    /**
     * 外采视频消耗按比例计算.
     * @param $data
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function videoCostRateOperation($data)
    {
        $rateDetail = VideoDailyCostConfigModel::select()->toArray();
        if (empty($rateDetail)) {
            return $data;
        }
        // 先校验是否是外采
        $storeId = ZcTaskModel::where('id', $data['task_id'])->value('store_id', 0);
        if ($storeId == 0) {
            return $data;
        }
        $storeIds = ZcStoreModel::where('company_id', '<>', 1)->column('id');
        if (! in_array($storeId, $storeIds)) {
            return $data;
        }

        $rate = 1;
        foreach ($rateDetail as $ontRate) {
            if ($data['task_id'] == $ontRate['task_id']) {
                if ($data['product_id'] == $ontRate['product_id']) {
                    $rate = $ontRate['rate'];
                    break;
                }
            }
        }
        if ($rate == 1) {
            return $data;
        }

        $costAfter = round($data['sum_cost'] * $rate, 3);
        $calculationInsert = [
            'file_id' => $data['file_id'],
            'cost_before' => $data['sum_cost'],
            'cost_after' => $costAfter,
            'stat_date' => $data['stat_date'],
            'rate' => $rate,
            'created_at' => date('Y-m-d H:i:s'),
            'update_at' => date('Y-m-d H:i:s'),
        ];

        VideoDailyCostCalculationModel::create($calculationInsert);
        $data['sum_cost'] = $costAfter;
        return $data;
    }

    /**
     * 视频版本消耗汇总.
     * @param string $date 日期
     * @param int $num 脚本编号
     * @param int $fileId 文件id
     */
    public static function cacheVideoAllVersionCost(string $date, int $num, int $fileId = 0): bool
    {
        Db::startTrans();
        try {
            $where = [
                ['stat_date', '=', $date],
            ];
            if ($fileId) {
                $where[] = ['file_id', '=', $fileId];
            }
            $videos = VideoDailyCostModel::where($where)
                ->group('file_id')
                ->order('id')
                ->column('file_id');
            if (! empty($videos)) {
                $allCount = count($videos);
                $pageLimit = ceil($allCount / CommonEnum::SHELL_NUM);
                $videos = array_slice($videos, intval($num * $pageLimit), (int) $pageLimit);
                // 分10個脚本
                foreach ($videos as $fileId) {
                    $fileId = self::getTopVersionFileId($fileId);
                    $allFileIds = MaterialCostService::getVideoAllVersionIds($fileId);
                    $cost = MaterialCostService::getVideoCostByFileIds($allFileIds, $date, $date);
                    if ($cost['oe_cost'] > 0 || $cost['ks_cost'] > 0 || $cost['qq_cost'] > 0) {
                        // 判断是否已存在
                        $isHas = VideoVersionDailyCostModel::where(['file_id' => $fileId, 'stat_date' => $date])
                            ->find();
                        if ($isHas) {
                            VideoVersionDailyCostModel::where('id', $isHas['id'])
                                ->update(['oe_cost' => $cost['oe_cost'], 'ks_cost' => $cost['ks_cost'], 'qq_cost' => $cost['qq_cost'], 'cost' => $cost['oe_cost'] + $cost['ks_cost'] + $cost['qq_cost']]);
                        } else {
                            $data = [
                                'file_id' => $fileId,
                                'stat_date' => $date,
                                'oe_cost' => $cost['oe_cost'],
                                'ks_cost' => $cost['ks_cost'],
                                'qq_cost' => $cost['qq_cost'],
                                'cost' => $cost['oe_cost'] + $cost['ks_cost'] + $cost['qq_cost'],
                            ];
                            VideoVersionDailyCostModel::create($data);
                        }
                    }

                    // 90天
                    $costNinety = MaterialCostService::getVideoNinetyCostByFileIds($allFileIds, $date, $date);
                    if ($costNinety['oe_cost'] > 0 || $costNinety['ks_cost'] > 0 || $costNinety['qq_cost'] > 0) {
                        // 判断是否已存在
                        $isHas = VideoVersionNinetyDailyCostModel::where(['file_id' => $fileId, 'stat_date' => $date])
                            ->find();
                        if ($isHas) {
                            VideoVersionNinetyDailyCostModel::where('id', $isHas['id'])
                                ->update(['oe_cost' => $costNinety['oe_cost'], 'ks_cost' => $costNinety['ks_cost'], 'qq_cost' => $costNinety['qq_cost'], 'cost' => $costNinety['oe_cost'] + $costNinety['ks_cost'] + $costNinety['qq_cost']]);
                        } else {
                            $data = [
                                'file_id' => $fileId,
                                'stat_date' => $date,
                                'oe_cost' => $costNinety['oe_cost'],
                                'ks_cost' => $costNinety['ks_cost'],
                                'qq_cost' => $costNinety['qq_cost'],
                                'cost' => $costNinety['oe_cost'] + $costNinety['ks_cost'] + $costNinety['qq_cost'],
                            ];
                            VideoVersionNinetyDailyCostModel::create($data);
                        }
                    }
                }
            }
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取版本1文件id.
     * @param int $fileId 文件id
     * @return int|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getTopVersionFileId(int $fileId)
    {
        // 查询是否任务流转
        $video = VideoModel::where('file_id', $fileId)->field('version,subtask_id,parent_id,video_type')->find();
        if ($video['version'] == 1 && $video['video_type'] == 2) {
            // 1版本且是竖版
            return $fileId;
        }
        if ($video['version'] == 1 && ! $video['subtask_id']) {
            // 1版本且是竖版
            return $fileId;
        }
        if ($video['subtask_id'] > 0) {
            $parents = VideoModel::where('subtask_id', $video['subtask_id'])
                ->where('version', 1)
                ->field('file_id,video_type')
                ->select()->toArray();
            if ($parents) {
                if (count($parents) == 1) {
                    return $parents[0]['file_id'];
                }
                foreach ($parents as $vv) {
                    if ($vv['video_type'] == 2) {
                        return $vv['file_id'];
                    }
                }
            }
        } else {
            $fileId = VideoModel::where('id', $video['parent_id'])->value('file_id');
        }
        return $fileId;
    }

    /**
     * @return int 获取脚本编号
     */
    public static function getNum(): int
    {
        return self::$runNum;
    }

    /**
     * @return Model 获取报表模型
     */
    public static function getReportModel(): Model
    {
        return self::$reportModel;
    }

    /**
     * @return int 获取日期
     */
    public static function getDate(): int
    {
        return self::$runDate;
    }

    /**
     * @return false|string 获取日期
     */
    public static function getStatDate()
    {
        return date('Y-m-d', strtotime(strval(self::getDate())));
    }

    /**
     * 获取报表数据.
     * @return array|bool|Model[]|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected static function getReportData()
    {
        $model = self::getReportModel();
        if (! $model instanceof Model) {
            return self::setError('报表模型错误');
        }

        $obj = $model->where('stat_date', self::getDate())->field('min(id) as min_id,max(id) as max_id')->findOrEmpty();
        $minId = $obj->getAttr('min_id') ?? 0;
        $maxId = $obj->getAttr('max_id') ?? 0;
        if ($maxId <= 0 || $minId <= 0) {
            return [];
        }

        $count = $maxId - $minId + 1;
        $len = intval(ceil($count / CommonEnum::SHELL_NUM));
        return $model->where('stat_date', self::getDate())
            ->field('id,account_id,advertiser_id,client_id,signature,stat_date,cost,is_sync')
            ->limit(self::getNum() * $len, $len)
            ->select();
    }
}
